import Vue from 'vue'
import VueRouter from 'vue-router'
import Admin from '_views/Admin'
import { isLogin } from '_utils'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'admin',
    component: Admin,
    meta: {
      needLogin: true,
      roles: ['admin', 'superAdmin', 'a', 'b']
    },
    children: [
      {
        path: '/',
        redirect: '/dashBoard'
      },
      {
        path: '/dashBoard',
        name: '仪表盘',
        meta: {
          needLogin: true,
          roles: ['admin', 'superAdmin', 'a', 'b']
        },
        component: () => import('_views/DashBoard')
      },
      {
        path: '/itemLists',
        name: '商品管理',
        meta: {
          needLogin: true,
          roles: ['admin', 'superAdmin', 'a', 'b']
        },
        component: () => import('_views/ItemLists')
      },
      {
        path: '/itemAdd',
        name: '增加商品',
        meta: {
          needLogin: true,
          roles: ['admin', 'superAdmin', 'a', 'b']
        },
        component: () => import('_views/ItemAdd')
      },
      {
        path: '/itemUpdate',
        name: '更新商品',
        meta: {
          needLogin: true,
          roles: ['admin', 'superAdmin', 'a', 'b']
        },
        component: () => import('_views/ItemUpdate')
      },
      {
        path: '/msgLists',
        name: '消息中心',
        meta: {
          needLogin: true,
          roles: ['admin', 'superAdmin', 'a', 'b']
        },
        component: () => import('_views/MsgLists')
      },
      {
        path: '/setting',
        name: '设置',
        meta: {
          needLogin: true,
          roles: ['superAdmin', 'a', 'b']
        },
        component: () => import('_views/Setting')
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    meta: {
      needLogin: false,
      roles: '*'
    },
    component: () => import('_views/Login')
  },
  {
    path: '*',
    component: () => import('_views/NotFound')
  },
  {
    path: '/noAuth',
    component: () => import('_views/NoPermission'),
    meta: {
      needLogin: false,
      roles: '*'
    }
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
// 添加路由前置守卫 做登录鉴权
router.beforeEach( (to, from, next) => {
  // 排除不需要登录的 某些路由
  if (to.meta.needLogin) {
    // 需要登录
    if (isLogin()) {
      // 登录了
      // 判断当前角色是否能够访问目标路由
      if (to.meta.roles === '*') {
        // 任何角色都可以访问
        next()
      } else {
        // 判断当前用户角色是否可以访问
        const role = localStorage.getItem('role')
        if (to.meta.roles.includes(role)) {
          // 可以访问
          next()
        } else {
          // 没有权限
          next('/noAuth')
        }
      }
    } else {
      next('/login')
    }
  } else {
    // 不需要登录
    next()
  }
})

export default router
